# -*- coding: utf-8 -*-
import datetime

from openerp import models, fields, api
from openerp.exceptions import Warning

class bc_planbill(models.Model):
    _name = 'bc.planbill'

    name = fields.Char()
    bussines_id = fields.Many2one('bc.bussines')
    contract_id = fields.Many2one('bc.contract')
    dttrans = fields.Datetime()
    state = fields.Selection([('draft', u'草稿'), ('audit', u'审核'), ('close', u'关闭')])
    audit_uid = fields.Many2one('res.users')
    audit_date = fields.Datetime()
    company_id = fields.Many2one('res.company', default=lambda self: self.env.user.company_id)
    planbill_detail_ids = fields.One2many('bc.planbill.detail', 'planbill_id')
    source = fields.Selection([('contract_audit', u'首次收款'), ('contract_rent', u'合同退租'), ('manual_input', u'手工录入'),
                               ('period_create', u'周期产生')], default='manual_input')

    @api.model
    def create(self, vals):
        vals['name'] = self.env['ir.sequence'].get('bc.planbill')
        vals['state'] = 'draft'
        return super(bc_planbill, self).create(vals)
    
    # 僅能刪除草稿狀態的資料
    @api.multi
    def unlink(self):
       if self.state not in ('draft') :
          raise Warning(_('state {0} can not be delete'.format(self.state)))
       return super(bc_planbill,self).unlink()    

    # 审核
    @api.model
    def btn_audit(self):
        self.write({'state': 'audit', 'audit_uid': self.env.user.id, 'audit_date': datetime.datetime.utcnow()})
        return True

    # 反审核
    @api.model
    def btn_unaudit(self):
        self.write({'state': 'draft', 'audit_uid': False, 'audit_date': False})
        return True

    def has_contract_audit(self, contract_id):
        """
        是否存在审核的合同数据
        """
        return self.search(
            [('contract_id', '=', contract_id), ('source', '=', 'contract_audit'), ('state', '<>', 'close')]).exists()

    def has_rent(self, contract_id):
        """
        是否存在退租的合同数据
        """
        return self.search(
            [('contract_id', '=', contract_id), ('source', '=', 'contract_rent'), ('state', '<>', 'close')]).exists()
